package com.hwhy.systemmonitoring.common.util;

import org.apache.commons.lang3.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符转换工具
 * @author LIFULIN
 * @className StringUtil
 * @description TODO 字符转换工具
 * @date 2020/4/28-18:28
 */
public class StringUtil {

    /**
     * 字节转换
     *
     * @param size 字节大小
     * @return 转换后值
     */
    public static String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else {
            return String.format("%d B", size);
        }
    }

    /**
     * Date转String
     *
     * @param format
     * @param date
     * @return
     */
    public static final String parseDateToStr(final String format, final Date date) {
        if (ObjectUtils.allNotNull(date)) {
            return new SimpleDateFormat(format).format(date);
        }
        return null;
    }


    /**
     * 提取数字
     *
     * @param str 字符
     * @return double
     */
    public static double getNumeric(String str) {
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        String s = m.replaceAll("").trim();
        return Double.parseDouble(s);
    }
}
